package com.wmm.servlet.student;

import com.wmm.bean.PageBean;
import com.wmm.bean.Student;
import com.wmm.service.StudentService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "Student_Servlet",urlPatterns = "/addStudent")
public class AddStudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String studentno = request.getParameter("studentno");
        String username = request.getParameter("username");
        String sex = request.getParameter("sex");
        String bdate = request.getParameter("bdate");
        String  email = request.getParameter("email");
        String extra = request.getParameter("extra");
        String classNo = request.getParameter("classNo");

        Student student = new Student(Integer.parseInt(studentno),username,sex,bdate,email,extra,classNo);
        StudentService studentService = new StudentService();
        boolean add = studentService.addStudentServer(student);
        if(add) {
            System.out.println("注册成功");

            //2. 调用service查询
            StudentService service = new StudentService();
            PageBean<Student> queryList = service.findStudentByPage("1","5");
            HttpSession session = request.getSession();
            session.setAttribute("queryList",queryList);
            response.sendRedirect("show.jsp");
        } else {
            HttpSession session = request.getSession();
            session.setAttribute("addError","可能是学号重复了，请重新输入正确的信息！");

            RequestDispatcher requestDispatcher = request.getRequestDispatcher("add.jsp");
            requestDispatcher.forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
